<?php
class Merchant_Service_CustomerBalance
{
	 
	public function __construct($options){
		 
	}
	
	/**
	* 用户 deposit Account
	* @param array $row
	* @return array|boolean success return boolean,false return array
	*/
	public static function depositMyAccount( $paymentOrderId, $options){
		$customerBalance = new Merchant_Model_CustomerBalance();
		$dbAdapter = $customerBalance->getAdapter();
		$status = $options['status'];//订单状态
		$transactionId = $options['transaction']; //支付事务ID
		$paymentFee  =0;
	    $dbAdapter->beginTransaction();
		$now = date('Y-m-d H:i:s');
		if(!$paymentOrderId) return false;
		try{
	
				$cdoObj = new Merchant_Model_CustomerDepositOrder();
			
				$paymentOrder =	$cdoObj->lockForUpdate($paymentOrderId);
				if($paymentOrder['cdo_payment_status']!='PD'&$status=='PD'){
					//开始充值
					$balance = $customerBalance->lockForUpdate($paymentOrder['customer_id']);
					$realValue = Default_Service_Currency::changeCurrency($paymentOrder['cdo_currency_value'],$paymentOrder['currency_code'],$balance['currency_code']);
					 
					if($realValue['ask']=='Success'){
						$pmObj = new Merchant_Model_PaymentMethod();
						$paymentMethod = $pmObj->getByCode($paymentOrder['pm_code']);
						
						$feeNote ='';
						if($paymentMethod['fee_leve']=='1'){
							$paymentBaseFee = Default_Service_Currency::changeCurrency($paymentMethod['pm_base_fee'],$paymentMethod['currency_code'],$balance['currency_code']);

							$paymentFee = $paymentBaseFee['value']+$paymentMethod['pm_fee_rate']*$paymentOrder['cdo_currency_value']/100;
							
							if($paymentMethod['pm_fee_rate']!=0)
							$feeNote .= '(1-'.$paymentMethod['pm_fee_rate'].'%)';	
							if($paymentMethod['pm_base_fee']!=0)
							$feeNote .= ' - '.$paymentMethod['pm_base_fee'].' X ('.$paymentMethod['currency_code'].')';
							
						}
						
						
						
						
						
						$note = "Deposit My Cff Account, Traction Id:".$transactionId."\n";
						$note .= 'Rate:'. $realValue['org_rate'].'/'. $realValue['dis_rate'].' = '.$realValue['rate']."\n";
						$note .=  $paymentOrder['cdo_currency_value'].' ('.$paymentOrder['currency_code'].') X '.$realValue['rate'];
						$note .= $feeNote;
						
						$balanceVal = $balance['cb_value']+$realValue['value']-$paymentFee; 
						$note .= " = ".$balanceVal." (".$balance['currency_code'].")";
						$balanceLog = array('customer_id'=>$paymentOrder['customer_id'],
											'cbh_base_value'=>$realValue['value'],
											'cbh_value'=>$paymentOrder['cdo_currency_value'],
											'currency_rate'=>$realValue['rate'],
											'currency_code'=>$paymentOrder['currency_code'],
											'ba_id'=>$paymentMethod['ba_id'],
											'cbh_note'=>$note,
											'cbh_type'=>1,
											'cbh_op_type'=>1,
											'cbh_class'=>0,
											'cbh_transaction_id'=>$transactionId,
											'user_id'=>0,
											'cbh_current_value'=>$balance['cb_value']+$realValue['value'],
											'cbh_arrive_time'=>$now,
											'cbh_add_time'=>$now
											);
						$cbhObj = new Merchant_Model_CustomerBalanceHistory();
						$logId	= $cbhObj->add($balanceLog);				
						if($paymentMethod['fee_leve']=='1'){							
							$feeLog = array('customer_id'=>$paymentOrder['customer_id'],
											'cbh_base_value'=>$paymentFee,
											'cbh_value'=>$paymentFee,
											'currency_rate'=>'1',
											'currency_code'=>$balance['currency_code'],
											'ba_id'=>$paymentMethod['ba_id'],
											'cbh_note'=>$note,
											'cbh_type'=>'-1',
											'cbh_op_type'=>1,
											'cbh_class'=>0,
											'cbh_transaction_id'=>$transactionId,
											'user_id'=>0,
											'cbh_current_value'=>$balanceVal,
											'cbh_arrive_time'=>$now,
											'cbh_refer_id'=>$logId,
											'cbh_add_time'=>$now
											);						
							
							$cbhObj->add($feeLog);	
						}						
						$balanceUpdate = array('cb_value'=>$balanceVal,'cb_last_update'=>$now); 
						$orderLog = array('cdo_id'=>$paymentOrder['cdo_id'],'customer_id'=>$paymentOrder['customer_id'],
								'cdo_status'=>$status,'cdl_note'=>'update to'.$status,'cdl_create_time'=>$now);
				
						$cdlObj = new Merchant_Model_CustomerDepositLog();
						$cdlObj->add($orderLog);
						 
					}else{
							$balanceUpdate = array('cb_last_update'=>$now);
					}
															 
					$customerBalance->update($balanceUpdate,$paymentOrder['customer_id']);//unlock balance
										
				} 
				
				
				
				
				$orders =		array('cdo_transcation_id'=>$transactionId,
								 'cdo_payment_status'=>$status,
								 'cdo_last_update'=>$now
								 );
								 
								 
				
				$cdoObj->update($orders,$paymentOrder['cdo_id']);//unlock deposit order
					 
				 
		     $dbAdapter->commit();
			 return true;
		}catch(Exception $e){
	    	$dbAdapter->rollback();
	    	return false;
	    }
		
	}
	/*
	*
	*正常帐户扣款/入款 或者HOLD
	*
	*/
	
	public static function procBalance($customerId,$options){
		
		if(!$customerId) return false;
		$paymentClass = $options['cbhClass'];//订单扣款类型 0:正常扣款/入款;1:冻结扣款/入款
		$refId = $options['refCode']; //参考记录ID 如订单号，产品号, ASN 号
		$appType = $options['appType']; //入账:1充值,2退款;借出:3:SKU,4:item,5:plant
		$cbhType = $options['cbhType']; //-1:扣款;1:充值
		$iniValue = $options['vale']; //金额
		$currencyCode = $options['currencyCode']; //币种
		$note = @$options['note']; //备注
		$opId = @$options['userId']; //后台操作人员ID/0系统操作/-1客户操作
		if(!$opId){
			$opId ='-1';	
		}
		$orgValue = $iniValue*$cbhType;
		$customerBalance = new Merchant_Model_CustomerBalance();
		 
		$now = date('Y-m-d H:i:s');
		$balance = $customerBalance->lockForUpdate($customerId);
		$valueRate = Default_Service_Currency::changeCurrency($iniValue,$currencyCode,$balance['currency_code']);
		$value = $valueRate['value']*$cbhType;
		$currentValue = $balance['cb_value']+$value;
		
		if($currentValue<0){//余额小于支付金额
			return false;
		}
		
			//$note = "Deposit My Cff Account, Traction Id:".$transactionId."\n";
		$balanceLog = array('customer_id'=>$customerId,
											'cbh_base_value'=>$value,
											'cbh_value'=>$orgValue,
											'currency_rate'=>$valueRate['rate'],
											'currency_code'=>$currencyCode,
											//'ba_id'=>$paymentMethod['ba_id'],
											'cbh_note'=>$note,
											'cbh_type'=>$cbhType,
											'cbh_op_type'=>$appType,
											'cbh_class'=>$paymentClass,
											'cbh_refer_id'=>$refId,
											'user_id'=>$opId,
											'cbh_current_value'=>$currentValue ,
											'cbh_arrive_time'=>$now,
											'cbh_add_time'=>$now
											);
	 									
		$cbhObj = new Merchant_Model_CustomerBalanceHistory();
		$cbhObj->add($balanceLog);											
		$balanceUpdate = array('cb_value'=>$currentValue,'cb_last_update'=>$now);
		if($paymentClass=='1')
			$balanceUpdate['cb_hold_value'] = $balance['cb_hold_value'] - $value;
		$customerBalance->update($balanceUpdate,$customerId);//unlock balance
		 
		 return true;					
	}
	
	/*
	*
	*release balance Value
	*对同一类型同一产品/订单多个扣费解冻
	*/
	
	public static function release($customerId,$refCode,$appType){
		
		if(!$customerId) return false;		
		if(!$refCode) return false;
		$now = date('Y-m-d H:i:s');
		$result['ask'] = "Success";
		$customerBalance = new Merchant_Model_CustomerBalance();
		$dbAdapter = $customerBalance->getDbTable()->getAdapter();
	    $dbAdapter->beginTransaction(); 
		
		try{
			$cbhObj = Merchant_Model_CustomerBalanceHistory();
			$cbhRows = $cbhObj->getHold($customerId,$refCode,$appType);
			
			
			$balance = $customerBalance->lockForUpdate($customerId);
			$balanceHold = $balance['cb_hold_value'];
			$returnVale = 0;
			foreach($cbhRows as $cbhRow){
			
			
			
					
					$valueRate = Default_Service_Currency::changeCurrency($iniValue,$cbhRow['currency_code'],$balance['currency_code']);
					$value = $valueRate['value'];
					$currentValue = $balance['cb_value']-$value;
					$note = "release $refCode."; 
					$balanceHold = $balanceHold - $valueRate['rate'];
					$returnVale += $valueRate['rate'];
					if($balanceHold>= 0){
					
					   /*解冻先不做添加记录（过于复杂）
						$balanceLog = array('customer_id'=>$customerId,
														'cbh_base_value'=>$value,
														'cbh_value'=>$orgValue,
														'currency_rate'=>$valueRate['rate'],
														'currency_code'=>$cbhRow['currency_code'],
														//'ba_id'=>$paymentMethod['ba_id'],
														'cbh_note'=>$note,
														'cbh_type'=>-$cbhRow['cbh_type'],
														'cbh_op_type'=>$cbhRow['cbh_op_type'],
														'cbh_class'=>3,
														'cbh_refer_id'=>$cbhRow['cbh_refer_id'],
														'user_id'=>0,
														'cbh_current_value'=>$currentValue ,
														'cbh_arrive_time'=>$now,
														'cbh_add_time'=>$now
														); 
														
					
						$cbhObj->add($balanceLog);											
								 
						*/ 
								
						
					
					}else{			
						$result['ask'] = "Error";
						$result['message'] = "on hold money less than release!";	
						 
						$dbAdapter->rollback();
						return $result;	
					}
					
					 
					
					$customerBalanceHistory = array('cbh_class'=>2);
					$cbhObj->update($customerBalanceHistory,$cbhRow['cbh_id']);		//TODO unlock balance history
			}
			
			$balanceUpdate = array('cb_value'=>$balance['cb_value']+$returnVale,'cb_hold_value'=>$balance['cb_hold_value']-$returnVale,'cb_last_update'=>$now); 							
			$customerBalance->update($balanceUpdate,$customerId);//unlock balance
			$dbAdapter->commit();
			return $result;	
		}catch(Exception $e){
	    	$dbAdapter->rollback();
	    	return false;
	    }	
												
	}
	 
	
	
	/**
	* 获取用户Balance信息
	* @param  $customerId
	* @return array 
	*/
	public static function getByCustomer($customerId){
		$customerBalance = new Merchant_Model_CustomerBalance();
		return $customerBalance->getByCustomer($customerId);
	}
	
	
	
	/**
	* 获取用户Balance Detail信息
	* @param  $options
	* @return array 
	*/
	public static function getByComdation($options,$type='*',$orderby=array()){
	 
		if(!isset($options['customer_id'])) return;
		//时间处理
		if(empty($options['startTime'])){
			$options['startTime'] = ''; 
		}else{
			$options['startTime'] = date('Y-m-d',strtotime("{$options['startTime']}"))." 00:00:00"; 
		}
		//时间处理
		if(empty($options['endTime'])){
			$options['endTime'] = ''; 
		}else{
			$options['endTime'] = date('Y-m-d',strtotime("{$options['endTime']}"))." 23:59:59"; 
		}	
		
		if(empty($options['cbh_op_type'])){
			$options['cbh_op_type'] = '';	
		}
			
		$start = 0;
		if($type!='*'){
			$type = "count(*) as count";
		}else{
			$type = "*";
			$start =($options['page'] -1)*$options['pageSize'];		
		}
		$customerBalance = new Merchant_Model_CustomerBalanceHistory();
		$rows = $customerBalance->getByComdation($options['customer_id'],$options['startTime'],$options['endTime'],$options['cbh_op_type'],$start,$options['pageSize'],$type,$orderby);
		$rows = $rows->toArray();
		return $rows;
	}

}